package cn.doitedu.es_api;

import org.apache.http.HttpHost;
import org.elasticsearch.action.search.SearchRequest;
import org.elasticsearch.action.search.SearchResponse;
import org.elasticsearch.client.RequestOptions;
import org.elasticsearch.client.RestClient;
import org.elasticsearch.client.RestHighLevelClient;
import org.elasticsearch.index.query.MatchQueryBuilder;
import org.elasticsearch.index.query.QueryBuilders;
import org.elasticsearch.search.SearchHit;
import org.elasticsearch.search.SearchHits;
import org.elasticsearch.search.builder.SearchSourceBuilder;

import java.io.IOException;

public class Demo {
    public static void main(String[] args) throws IOException {

        // 先构造客户端对象
        RestHighLevelClient client = new RestHighLevelClient(RestClient.builder(new HttpHost("doitedu", 9200, "http")));



        // 构造请求对象
        SearchRequest request = new SearchRequest("profile_test");


        // 构造查询条件
        MatchQueryBuilder matchQueryBuilder = QueryBuilders.matchQuery("tag_03_01", "省电");


        // 将查询条件放入请求对象
        request.source(new SearchSourceBuilder().query(matchQueryBuilder));

        // 用客户端发起请求
        SearchResponse response = client.search(request, RequestOptions.DEFAULT);


        // 解析结果
        SearchHits hits = response.getHits();
        SearchHit[] hits1 = hits.getHits();

        for (SearchHit hit : hits1) {
            String sourceAsString = hit.getSourceAsString();

            System.out.println(sourceAsString);
        }

    }

}
